//
//  KADBManager.swift
//  kano
//
//  Created by Sophia on 2024/8/20.
//

import UIKit

struct KADBDBManager {
    
    static let userKey = "KUserData"
    static func ka_saveUser(data: Codable) {
        let encoder = JSONEncoder()
        do {
            let encodeData = try encoder.encode(data)
            UserDefaults.standard.set(encodeData, forKey: userKey)
            //print("-----------------------save user success")
        } catch {
            //print("Failed to encode person: \(error)")
        }
    }
    static func ka_getUser() -> KAUser? {
        let decoder = JSONDecoder()
        if let data = UserDefaults.standard.data(forKey: userKey) {
            do {
                let user = try decoder.decode(KAUser.self, from: data)
                //print("-----------------------get user:\n \(user) \n-----------------------↑")
                return user
            } catch {
                //print("Failed to decode person: \(error)")
                return nil
            }
        }
        return nil
    }
    static func ka_removeCurrentUser() {
        UserDefaults.standard.removeObject(forKey: userKey)
    }
    
    //get document path
    static func ka_documentAppendFilePath(fileName: String) -> String {
        let var_documentsPath = FileManager.ka_documentsPath()
        let var_filePath = "\(var_documentsPath)/\(fileName)"
        if !FileManager.default.fileExists(atPath: var_filePath, isDirectory: UnsafeMutablePointer(nil)) {
            do {
                try FileManager.default.createDirectory(atPath: var_filePath, withIntermediateDirectories: true)
                return var_filePath
            } catch {
                print("other fail")
            }
        }
        return var_filePath
    }
    
    //MARK: - save with path and name
    // （fileName != filename && fileName = Object name）
    @discardableResult
    static func ka_saveInDocument(object: AnyObject, filePath: String, fileName: String) -> Bool {
        let var_path = ka_documentAppendFilePath(fileName: filePath)
        let var_finalPath: String = "\(var_path)/\(fileName)"
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
            try data.write(to: URL(fileURLWithPath: filePath))
            return true
        } catch {
            print("Error saving object: \(error)")
            return false
        }
        print("save filePath === \(var_finalPath)")
    }
    // get from document
    static func ka_getObject(filePath: String, fileName: String) -> Any? {
        let path = ka_documentAppendFilePath(fileName: filePath)
        let fullPath = "\(path)/\(fileName).archive"
        if let obj = NSKeyedUnarchiver.unarchiveObject(withFile: fullPath) {
            print("get filePath ===== \(fullPath)")
            return obj
        } else {
            print("Failed to unarchive object from filePath: \(fullPath)")
            return nil
        }
    }
    
    //MARK: save with name
    @discardableResult
    static func ka_saveInDocument(object: Any, fileName: String) -> Bool {
        let path = ka_documentAppendFilePath(fileName: fileName)
        let filePath: String
        if fileName.contains("/") {
            let components = fileName.components(separatedBy: "/")
            if let lastComponent = components.last {
                filePath = "\(path)/\(lastComponent).archive"
            } else {
                return false
            }
        } else {
            filePath = "\(path)/\(fileName).archive"
        }
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
            try data.write(to: URL(fileURLWithPath: filePath))
            return true
        } catch {
            print("Error saving object: \(error)")
            return false
        }
        print("save filePath === \(filePath)")
    }
    static func ka_getObject(by fileName: String) -> Any? {
        let path = ka_documentAppendFilePath(fileName: fileName)
        let filePath: String
        if fileName.contains("/") {
            let components = fileName.components(separatedBy: "/")
            if let lastComponent = components.last {
                filePath = "\(path)/\(lastComponent).archive"
            } else {
                return nil
            }
        } else {
            filePath = "\(path)/\(fileName).archive"
        }
        if let obj = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) {
            return obj
        } else {
            print("Failed to unarchive object from filePath: \(filePath)")
            return nil
        }
    }
    //MARK: remove
    static func removeObject(by fileName: String) {
           let path = ka_documentAppendFilePath(fileName: fileName)
           let filePath: String
           if fileName.contains("/") {
               let components = fileName.components(separatedBy: "/")
               if let lastComponent = components.last {
                   filePath = "\(path)/\(lastComponent).archive"
               } else {
                   print("Invalid file name format")
                   return
               }
           } else {
               filePath = "\(path)/\(fileName).archive"
           }
           do {
               try FileManager.default.removeItem(atPath: filePath)
               print("Successfully removed file at path: \(filePath)")
           } catch {
               print("Error removing file at path: \(filePath), error: \(error)")
           }
       }
    

    //MARK: save image
    static func ka_saveImageToCacheUseImage(image: UIImage, fileName: String) -> Bool {
        let var_path = ka_documentAppendFilePath(fileName: fileName)
        let var_finalPath: String = "\(var_path)/\(fileName).png"
        do {
            try image.pngData()?.write(to: URL(fileURLWithPath: var_finalPath))
            return true
        } catch {
            print("other fail")
            return false
        }
    }
    
    //MARK: read image
    static func ka_getCacheImageUseImagePath(fileName: String) -> UIImage? {
        let var_path = ka_documentAppendFilePath(fileName: fileName)
        let var_finalPath: String = "\(var_path)/\(fileName).png"
        guard let var_image = UIImage.init(contentsOfFile: var_finalPath) else {
            return UIImage(named: "icon_defaultIcon")
        }
        return var_image
    }

}


